package cn.edu.bjtu.toychange.dao;

import java.util.List;

import org.hibernate.Session;

import cn.edu.bjtu.toychange.entity.User;

public class UserDao extends BaseDao {
	private Session session;
	
	public UserDao() {
		session = getSession();
	}
	
	// 添加或修改用户
	public boolean saveUser(User user) {
		session.beginTransaction();
		try {
			session.saveOrUpdate(user);
		} catch (Exception e) {
			return false;
		}
		
		session.close();
		
		return true;
	}

	// 删除用户
	public boolean deleteUser(int userID) {
		session.beginTransaction();
		try {
			session.delete(session.load(User.class, userID));
		} catch (Exception e){
			return false;
		}
		
		session.close();
		
		return true;
	}

	// 获取用户
	public User getUser(int userID) {
		session.beginTransaction();
		User user = (User) session.get(User.class, userID);
		session.close();

		return user;
	}
	
	// 锁定用户
	public boolean lockUser(int userID) {
		User user = getUser(userID);
		
		try {
			user.setU_islocked((byte)1);
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}
	
	//解锁用户
	public boolean unLockUser(int userID) {
		User user = getUser(userID);
		
		try {
			user.setU_islocked((byte)0);
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}
	
	//得到所有的用户
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		session.beginTransaction();
		List<User> userAll = session.createQuery("SELECT * FROM User").list();
		session.close();
		
		return userAll;
	}
}
